<template>
  <el-dialog title="导入点位" :visible.sync="show" :close-on-click-modal="false" :show-close="!disableAction" width="800px" @closed="closed">
    <el-upload ref="upload" accept=".xls,.xlsx" :limit="1" :on-exceed="onExceed" :on-change="onChange" :disabled="uploading" action="" :auto-upload="false" :show-file-list="false">
      <el-button :loading="uploading">{{ uploading ? '上传验证中...' : '选择Excel' }}</el-button>
    </el-upload>

    <div slot="footer" class="flex-sb">
      <a target="_blank" :href="templateURL" download>
        <el-button type="success">下载模板</el-button>
      </a>
      <el-button :disabled="disableAction" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { importSpot } from '@/api/cq/patrol'
const baseURL = process.env.VUE_APP_BASE_API
const templateURL = `${baseURL}/profile/template/excel/巡更点导入模版实例.xlsx`
export default {
  data() {
    return {
      templateURL,
      show: false,
      projectId: '',
      isImported: false, // 成功导入
      uploading: false,
      failedURL: '' // 验证失败的文件链接
    }
  },
  computed: {
    disableAction() {
      return this.uploading
    }
  },
  methods: {
    closed() {
      if (this.isImported) this.$emit('ok')
      this.projectId = ''
      this.isImported = false
      this.uploading = false
      this.$refs.upload.clearFiles()
    },
    open({ projectId }) {
      if (!projectId) return this.$message.error('参数错误：项目ID不能为空')
      this.show = true
      this.projectId = projectId
    },
    onExceed() {
      this.msgInfo('只能选择 1 个文件')
    },
    async onChange(file) {
      if (!(file || {}).raw) return this.$message.warning('请选择文件')

      const formData = new FormData()
      formData.append('projectId', this.projectId)
      formData.append('file', file.raw)

      this.uploading = true
      const res = await importSpot(formData).catch(() => false)
      this.uploading = false
      this.$refs.upload.clearFiles()
      if (res === false) return

      // 下载文件
      if (res.headers['content-type'] === 'application/vnd.ms-excel') {
        this.msgError('模板校验失败，请查看下载的文件并更改')
        const elink = document.createElement('a')
        elink.download = file.name
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(new Blob([res.data]))
        elink.click()
        return
      }

      this.msgSuccess('上传成功')
    }
  }
}
</script>
